package com.sc.portal.controller;

import com.sc.common.pojo.CartItem;
import com.sc.common.pojo.CommonResult;
import com.sc.portal.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @auther sc
 * @Date 2017/11/7
 */
@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @RequestMapping("/add/{itemID}")
    public String addItem(@RequestParam(value = "itemNum",defaultValue = "1") Integer itemNum,
                                @PathVariable("itemID") Long itemId,
                                HttpServletRequest request,
                                HttpServletResponse response){
        CommonResult result = cartService.addItem(itemId, itemNum, request, response);
        return "cart-success";
    }
    @RequestMapping("/cart")
    public String listCart(HttpServletRequest request, Model model){
        List<CartItem> cartItems = cartService.listCart(request);
        model.addAttribute("cartList",cartItems);
        return "cart";
    }

    @RequestMapping("/update/num/{id}/{num}")
    @ResponseBody
    public CommonResult updateNum(@PathVariable("id")Long id,@PathVariable("num") int num,
                                  HttpServletRequest request,
                                  HttpServletResponse response){
        return cartService.updateNum(id,num,request,response);
    }
    @RequestMapping("/delete/{id}")
    public String deleteItem(@PathVariable("id")Long id,HttpServletRequest request,HttpServletResponse response){
        CommonResult result = cartService.deleteItem(id, request, response);
        return "redirect:/cart/cart.html";
    }

}
